var info = location.search.substr(1).split("id=")[1];
async function fn() {
  //获取传入的id
  let movies;
  let types;

  //获取评论
  var comments = [];
  //获取电影
  var moviesinfo = [];
  await $.ajax({
    url: "https://www.fastmock.site/mock/bb4157f45a0b5ffdcb3f6d984517a6c0/woniuMovie/getAllMovies",
    success: function (data) {
      $("#swj").css("display", "none")
      movies = data.movies;
      movies.filter(function (v, i) {
        if (v.id == info) {
          var $div = $('<div class="content"></div>');
          $div.html(
            `<div class="photo">
          <img src="${v.imgSrc}">
          </div>
          <div class="formalContent">
          <div class="title">
              <p>${v.title}</p>
              <span id="type">${v.movieType}</span>
              <br>
              <span>中国大陆/${v.duration}</span>
              <br>
              <span>${v.release.substring(0, 16)}</span>
              <button>
                  <img src="../images/详情img/star.png">
                  <span class="specialSpan">想看</span>
              </button>
              <button>
                  <img src="../images/详情img/star1.png">
                  <span class="specialSpan">评分</span>
              </button>
              <button class="specialButton">特惠购票</button>
          </div>
          <div class="evaluate">
              <p>蜗牛口碑</p>
              <div class="box1">
                  <span>${v.score}</span>
              </div>
              <div class="box2">
                  <ul>
                      <li>
                          <img src="../images/详情img/star2.png">
                      </li>
                      <li>
                          <img src="../images/详情img/star2.png">
                      </li>
                      <li>
                          <img src="../images/详情img/star2.png">
                      </li>
                      <li>
                          <img src="../images/详情img/star2.png">
                      </li>
                      <li>
                          <img src="../images/详情img/star3.png">
                      </li>
                  </ul>
                  <span>13.3万人评分</span>
              </div>
              <p>累计票房</p>
              <h1>2.38亿</h1>
          </div>`
          );
          $('.top').append($div);
          $('.moviesName').text(`蜗牛电影 > 电影 > ${v.title}`)
          $('#introduce').text(`${v.desc}`)
        }
      })

      movies.filter(function (v, i) {
        if (v.id == info) {
          comments.push(v.comments)
        }
      })

      movies.filter(function (v, i) {
        moviesinfo.push(v);
        //上半部分数据
        if (i < 9) {
          var $div = $("<div class='movieCard'></div>");
          $div.html(` <img src="${v.imgSrc}">
              <p>${v.title}</p>
              <span>暂无评论</span>`)
          $('#box2').append($div);
        }
      })
    }
  })

  //电影类别
  await $.ajax({
    url: "https://www.fastmock.site/mock/bb4157f45a0b5ffdcb3f6d984517a6c0/woniuMovie/getAllTypes",
    success: function (data) {
      var str = [];
      types = data.types;
      types.filter(function (v) {
        var id = $('#type').text().split(",");
        for (i = 0; i < id.length; i++) {
          if (v.id == id[i]) {
            str.push(v.name)
          }
        }
      })
      str.join('')
      $('#type').text(str);
    }
  })

  //获取评论
  for (var i = 0; i < comments[0].length; i++) {
    var Number = parseInt(Math.random() * 11);
    var Number2 = parseInt(Math.random() * 500);
    var month = parseInt(Math.random() * 12 + 1);
    var day = parseInt(Math.random() * 30);
    var hour = parseInt(Math.random() * 24);
    var minutes = parseInt(Math.random() * 59);
    if (i == 0) {
      var $newtext = $('<div class="talkAbout under"></div>');
      $newtext.html(`<div class="headImg"><img src="../images/详情img/touxiang.png"></div><div class="talkContent"><p>&nbsp;hp</p><span>2021/${month}/${day} ${hour}:${minutes}</span><ul class="star star${Number}"></ul><button><img src="../images/详情img/good.png"><span class="newSpan">${Number2}</span></button><span class="text">${comments[0][i]}</span></div>`);
    } else {
      var $newtext = $('<div class="talkAbout under"></div>');
      $newtext.html(`<div class="headImg"><img src="../images/详情img/touxiang.png"></div><div class="talkContent"><p>&nbsp;hp</p><span>2021/${month}/${day} ${hour}:${minutes}</span><ul class="star star${Number}"></ul><button><img src="../images/详情img/good.png"><span class="newSpan">${Number2}</span></button><span class="text">${comments[0][i]}</span></div>`);
    }
    $('.tab1').append($newtext);
  }

  // userComments
  let users = JSON.parse(localStorage.getItem("users"));
  let loginUser = localStorage.getItem("loginUser");
  if (loginUser) {
    loginUser = JSON.parse(loginUser);
    users.forEach(user => {
      if (user.user == loginUser.user) {
        loginUser.comments = user.comments
      }
    });
    $('.tab1').append($(
      `<div class="talkAbout under">
      <div class="headImg">
      <img src="../images/详情img/touxiang.png">
      </div>
      <div class="talkContent">
      <p>${loginUser.comments.userPhone}</p>
      <span>${loginUser.comments.time}</span>
        <ul class="star star${Number}"></ul>
        <button>
        <img src="../images/详情img/good.png">
        <span class="newSpan">${Number2}</span>
        </button>
        <span class="text">${loginUser.comments.content}</span>
        </div>
        </div>`
    ));
  }


  $(".specialButton").on('click', function () {
    location.assign(`../html/cinema.html${location.search}`)
  });
}

fn();



//打开评论界面
function newwrite() {
  $(".interface1").slideToggle();
}
//关闭评论界面
function textclose() {
  $(".interface1").slideToggle();
}

// 获取时间
function getTime(format) {
  var now = new Date();
  //将YYYY转为当前的年份
  format = format.replace(/YYYY/g, now.getFullYear());
  //将MM转为当前的月份，本身api获取的0~11，所以要加1
  format = format.replace(/MM/g, now.getMonth() + 1);
  // 将DD转为当前日期
  format = format.replace(/DD/g, now.getDate());
  // 将hh转为当前小时数
  format = format.replace(/hh/g, now.getHours());
  //将mm转为当前分钟数
  format = format.replace(/mm/g, now.getMinutes());
  //将ss转为当前秒数
  format = format.replace(/ss/g, now.getSeconds());

  return format;
};

//刷新界面之后运行相应函数
window.onload = function () {
  $('.specialA').css({ 'border-bottom': "2px solid #fa9334", 'color': "#fa9334" })
  $('#tab').on('click', 'li', function () {
    //tab切换
    //进行判断，并显示相应内容
    if ($(this).text() == "介绍") {
      $(this).find('a').css({ 'border-bottom': "2px solid #fa9334", 'color': "#fa9334" })
      $(this).next().find('a').css({ 'border-bottom': "", 'color': "black" })
      $('.tab1').css({ 'display': "block" })
      $('.tab2').css({ 'display': "none" })
    } else {
      $(this).find('a').css({ 'border-bottom': "2px solid #fa9334", 'color': "#fa9334" })
      $(this).prev().find('a').css({ 'border-bottom': "", 'color': "black" })
      $('.tab2').css({ 'display': "block" })
      $('.tab1').css({ 'display': "none" })
    }
  })
  //获取星星数量
  var star;
  $('#star').on('click', 'li', function () {
    star = $(this).attr('id').split("star").join('');
    $('#star').css({ 'background-position': `200px ${-30 * star}px` })
  })
  // 发布评论
  $('#ok').on('click', function () {
    let loginUser = localStorage.getItem("loginUser");
    var givegood = 0;
    var time = getTime("YYYY/MM/DD hh:mm");
    var name;
    if (loginUser != "") {
      loginUser = JSON.parse(loginUser);
      if (loginUser.name) {
        name = loginUser.name;
      } else {
        name = loginUser.user;
      }
      var $newtext = $('<div class="talkAbout"></div>');
      if (star >= 1) {
        $newtext.html(`<div class="headImg"><img src="../images/详情img/touxiang.png"></div><div class="talkContent"><p>&nbsp;${name}</p><span>${time}</span><ul class="star star${star}"></ul><button><img src="../images/详情img/good.png"><span class="newSpan">${givegood}</span></button><span class="text">${$('#talk').val()}</span></div>`);
      } else {
        $newtext.html(`<div class="headImg"><img src="../images/详情img/touxiang.png"></div><div class="talkContent"><p>&nbsp;hp</p><span>${time}</span><ul class="star"></ul><button><img src="../images/详情img/good.png"><span class="newSpan">${givegood}</span></button><span class="text">${$('#talk').val()}</span></div>`);
      }
      $('.tab1').append($newtext);
      $(".interface1").slideUp();
      saveComments();
      $('#star').css({ 'background-position': `200px 0px` })

      star = 0;
    } else {
      alert('请先登录');
      $(".interface1").slideUp();
      setTimeout(() => {
        $(".interface").slideDown();
        $('#tab-login').css({ 'border-bottom': "2px solid red" })
      }, 1000);
    }
  })

  function saveComments() {
    let users = JSON.parse(localStorage.getItem("users"))
    let loginUser = JSON.parse(localStorage.getItem("loginUser"))
    users.map(user => {
      if (user.user == loginUser.user) {
        user.comments = {
          userPhone: loginUser.user,
          movieid: info,
          content: $("#talk").val(),
          time: getTime('YYYY-MM-DD hh:mm:ss'),
          score: -$("#star").css("backgroundPositionY").replace("px", "") / 30
        }
      }
    });
    localStorage.setItem("users", JSON.stringify(users));
  }

}

